package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wephone.Student.R;
import com.wephone.Student.bean.CareMeOrMyCareResponse;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;
import com.wephone.Student.util.RoundImageView;

public class GroupMeOrMyGroupListActivity extends BaseActivity {
	private boolean isShowCareMe = false;
	private PullToRefreshView pullToRefreshListView;
	private ListView listView;
	private ListViewAdapter adapter;
	private List<UserInfoData> results = new ArrayList<UserInfoData>();
	private String uid;

	private AsyncHttpResponseHandler getHandler(){
		AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String result) {
				if(!TextUtils.isEmpty(result)){
					try{
						Gson gson = new Gson();
						CareMeOrMyCareResponse res = (CareMeOrMyCareResponse)gson.fromJson(result, CareMeOrMyCareResponse.class);
						if(res.getErrNo()!=null && !res.getErrNo().equals("0")){
							if(isShowCareMe){
								Toast.makeText(getApplicationContext(), "暂无粉丝", Toast.LENGTH_SHORT).show();
							}else{
								Toast.makeText(getApplicationContext(), "暂无关注", Toast.LENGTH_SHORT).show();
							}
						}else{
							if(res.getData()!=null && res.getData().getList()!=null && res.getData().getList().getuInfo()!=null && res.getData().getList().getuInfo().size()<Constants.PAGE_SIZE){
								adapter.hasMore = false;
							}else{
								adapter.pageIdx++;
							}
							results.addAll(res.getData().getList().getuInfo());
							adapter.notifyDataSetChanged();
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		};
		return handler;
	}
	

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_care_me_or_my_care_list);
		
		init();
	}
	
	private void init(){
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("userData", results.get(arg2));
				startActivity(new Intent(getApplicationContext(),UserInfoDetailActivity.class).putExtras(bundle));
			}});
		pullToRefreshListView = (PullToRefreshView)findViewById(R.id.pull_refresh_listview);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			uid = bundle.getString("uid");
			isShowCareMe = bundle.getBoolean("isShowCareMe",false);
			if(isShowCareMe){
				((TextView)findViewById(R.id.top_bar_title)).setText("我的粉丝");
			}else{
				((TextView)findViewById(R.id.top_bar_title)).setText("我的关注");
			}
			if(!TextUtils.isEmpty(uid) && !uid.equals(BaseActivity.getMyInfo(getApplicationContext()).getuId())){
				String username = bundle.getString("username");
				if(!TextUtils.isEmpty(username)){
					if(isShowCareMe){
						((TextView)findViewById(R.id.top_bar_title)).setText(username+"的粉丝");
					}else{
						((TextView)findViewById(R.id.top_bar_title)).setText(username+"的关注");
					}
				}
			}
			pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
				@Override
				public void onHeaderRefresh(PullToRefreshView view) {
					results.clear();
					adapter.hasMore = true;
					adapter.pageIdx = 1;
					
					RequestParams params = new RequestParams();
					params.put("uId", uid);
					params.put("Page", "1");
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					if(isShowCareMe){
						HttpClient.getInstance().get(Constants.API_GET_CARE_ME_LIST_URL, params, getHandler());
					}else{
						HttpClient.getInstance().get(Constants.API_GET_MY_CARE_LIST_URL, params, getHandler());
					}
				}
			});
			pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
				@Override
				public void onFooterRefresh(PullToRefreshView view) {
					if(!adapter.hasMore){
						pullToRefreshListView.onFooterRefreshComplete();
						return;
					}
					RequestParams params = new RequestParams();
					params.put("uId", uid);
					params.put("Page", ""+adapter.pageIdx);
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					if(isShowCareMe){
						HttpClient.getInstance().get(Constants.API_GET_CARE_ME_LIST_URL, params, getHandler());
					}else{
						HttpClient.getInstance().get(Constants.API_GET_MY_CARE_LIST_URL, params, getHandler());
					}
				}
			});
			
			RequestParams params = new RequestParams();
			params.put("uId", uid);
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			if(isShowCareMe){
				HttpClient.getInstance().get(Constants.API_GET_CARE_ME_LIST_URL, params, getHandler());
			}else{
				HttpClient.getInstance().get(Constants.API_GET_MY_CARE_LIST_URL, params, getHandler());
			}
		}
	}
	
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.default_user_logo)
    .showImageOnFail(R.drawable.default_user_logo)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
//    .displayer(new RoundedBitmapDisplayer(1000))
    .build();

	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_focus_list_item, null);
			}
			UserInfoData data = results.get(position);
			TextView itemName = (TextView)convertView.findViewById(R.id.item_name);
			itemName.setText(data.getuName());
			TextView itemCountry = (TextView)convertView.findViewById(R.id.item_country);
			itemCountry.setText(sdf.format(new Date(Long.parseLong(data.getuTS())*1000)));
			TextView universityText = (TextView)convertView.findViewById(R.id.item_university);
			universityText.setText(data.getuConstellation());
			TextView itemSign = (TextView)convertView.findViewById(R.id.item_signature);
			itemSign.setText(data.getuSign());
			
			TextView genderText = (TextView)convertView.findViewById(R.id.item_gender_text);
			ImageView genderImage = (ImageView)convertView.findViewById(R.id.item_gender);
			if(data.getuGender().equals("0")){
				genderImage.setImageResource(R.drawable.online_male);
				genderText.setText("男");
			}else{
				genderImage.setImageResource(R.drawable.online_female);
				genderText.setText("女");
			}
			
			if(!TextUtils.isEmpty(data.getuIcon())){
				RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.item_image);
				String endStr = data.getuIcon().substring(data.getuIcon().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+data.getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+data.getuInfo().getuIcon(), itemImage, options);
			}
			
			return convertView;
		}		
	}
	
}
